import { ALLOW_ANON } from '@/decorators/allow-anon.decortors';
import { UsersService } from '@/modules/users/users.service';
import { ExecutionContext, Inject, Injectable, UnauthorizedException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
  constructor(
    private readonly reflector: Reflector,
    @Inject(UsersService)
    private readonly userService: UsersService
  ) {
    super();
  }
  async canActivate(context: ExecutionContext): Promise<boolean> {
    const allowAnon = this.reflector.getAllAndOverride<boolean>(ALLOW_ANON, [
      context.getHandler(),
      context.getClass(),
    ]);
    if (allowAnon) {
      return true;
    }
    const req = context.switchToHttp().getRequest();
    const accessToken = req.get('Authorization');
    if (!accessToken) {
      throw new UnauthorizedException('请求未携带token');
    }
    const userId = this.userService.verifyToken(accessToken);
    if (!userId) {
      throw new UnauthorizedException('token错误');
    }
    return super.canActivate(context) as Promise<boolean>;
  }
}
